import 'package:cached_network_image/cached_network_image.dart';
import 'package:family_expense/features/bank_card/models/bank.dart';
import 'package:family_expense/features/bank_card/models/bank_card.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter_core/my_flutter_core.dart';

class BankShared {
  /// Shows a pick modal for bank selection.
  /// [banks] is the list of all banks. The [ListTile] is generated based on it.
  /// [bankCard] is current bankCard for making [ListTile] selected.
  static void showBankModalBottomSheet(
    BuildContext context,
    List<Bank> banks,
    ValueChanged<Bank> onTap, {
    BankCard? bankCard,
  }) {
    final listTiles = banks
        .map(
          (p) => ListTile(
            leading: BankLogo(p),
            title: Text(p.name!),
            selected: p.id == bankCard?.bank?.id,
            onTap: () => onTap(p),
          ),
        )
        .toList();

    showModalBottomSheet<void>(
      context: context,
      builder: (context) => Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const SizedBox(height: 20.0),
          Text('银行', style: Theme.of(context).textTheme.titleLarge),
          const SizedBox(height: 20.0),
          SizedBox(height: 180.0, child: ListView(children: listTiles)),
        ],
      ),
    );
  }

  // Gets the credit card statement date range text.
  static String getCreditCardStatementDateRangeDescription(BankCard? bankCard) {
    var text = '';

    if (bankCard?.isCreditCard == true &&
        bankCard?.statementDate.isNotNullOrEmpty == true) {
      final currentMonthStatementDay = int.parse(bankCard!.statementDate!) - 1;

      text +=
          '账单周期为上月${bankCard.statementDate}号至本月${currentMonthStatementDay > 0 ? '$currentMonthStatementDay号' : '月底'}';
    }

    return text;
  }
}

/// Gets the bank logo widget based on [bank].
class BankLogo extends StatelessWidget {
  const BankLogo(this.bank, {super.key, this.width = 22.0});

  final Bank bank;
  final double width;

  @override
  Widget build(BuildContext context) {
    return CachedNetworkImage(imageUrl: bank.logoUrl!, width: width);
  }
}
